package base

import (
	"fmt"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"infra"
	"log"
	"os"
	"time"
)
import "gorm.io/driver/mysql"

var mainDB *gorm.DB

func GetMainDatabase() *gorm.DB {
	return mainDB
}

type DatabaseStarter struct {
	infra.BaseStarter
}

func (d *DatabaseStarter) Setup(ctx infra.StarterContext) {
	log.Println("Setup database starter...")
	// 读取配置文件
	c := Config()
	// 加载配置
	// ip = 127.0.0.1
	// port = 3306
	// user = root
	// password = 123456
	// database = envelop
	// root:123456@tcp(127.0.0.1:3306)/envelop?charset=utf8mb4&parseTime=True&loc=Local
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		c.GetString("mysql.user"),
		c.GetString("mysql.password"),
		c.GetString("mysql.ip"),
		c.GetInt("mysql.port"),
		c.GetString("mysql.database"))
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold:             time.Second,
			Colorful:                  false,
			IgnoreRecordNotFoundError: false,
			LogLevel:                  logger.Info,
		},
	)
	var err error
	mainDB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		SkipDefaultTransaction: false,
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   "",
			SingularTable: true,
		},
		FullSaveAssociations:                     false,
		Logger:                                   newLogger,
		DisableForeignKeyConstraintWhenMigrating: true,
	})
	if err != nil {
		log.Fatal(err)
	}
}
